package com.zcgame.loadimagedemo.utils

import android.annotation.TargetApi
import android.content.Context
import android.content.pm.PackageManager.PERMISSION_GRANTED
import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager

/**
 *@author:huangLJ
 *@date:2021/7/19 09:28
 */

internal class PermissionUtils {
    private val TAG = PermissionUtils::class.java.simpleName
    private var permissionFragment: PermissionFragment? = null

    constructor(activity: FragmentActivity) {
        getSupportFragment(activity.supportFragmentManager)
    }
    constructor(fragment: Fragment?) {
        getSupportFragment(fragment?.childFragmentManager)
    }

    private fun getSupportFragment(fragmentManager: FragmentManager?): PermissionFragment? {
        findPermissionFragment(fragmentManager)
        val isNewInstance = permissionFragment == null
        if(isNewInstance && fragmentManager != null){
            permissionFragment =
                PermissionFragment()
            fragmentManager.beginTransaction().add(permissionFragment!!,TAG).commit()
        }
        return permissionFragment
    }

    private fun findPermissionFragment(fragmentManager: FragmentManager?): Fragment? {
        return fragmentManager?.findFragmentByTag(TAG)
    }

    @TargetApi(Build.VERSION_CODES.M)
    fun need(permissions: Array<String>): PermissionFragment {


        if(permissionFragment == null){
            throw IllegalArgumentException("fragment must be not null !!")
        }
        permissionFragment!!.request = true
        permissionFragment!!.permissions = permissions

        if(permissionFragment!!.isAdded){
            if (checkPermission(permissions)) return permissionFragment!!
            permissionFragment!!.requestPermissions(permissions,10086)
            permissionFragment!!.request = false
        }
        return permissionFragment!!
    }
    private fun checkPermission(permissions: Array<String>): Boolean {
        val allGranted = permissions.all {
            ContextCompat.checkSelfPermission(
                permissionFragment!!.context!!,
                it
            ) == PERMISSION_GRANTED
        }
        if (allGranted) return true
        return false
    }



    class PermissionFragment:Fragment(){
        lateinit var permissions: Array<String>
        private var attach = false
        var request = false
        private var subscribe: Subscribe? =  null
        override fun onRequestPermissionsResult(
            requestCode: Int,
            permissions: Array<String>,
            grantResults: IntArray
        ) {
            val isGranted =  permissions.all {
                 ContextCompat.checkSelfPermission(
                    activity!!.baseContext,
                    it
                ) == PERMISSION_GRANTED
            }
            subscribe?.onResult(isGranted)
            if(fragmentManager?.findFragmentByTag(PermissionUtils::class.java.simpleName) == this){
                fragmentManager?.beginTransaction()?.remove(this)?.commit()
            }
        }

        fun subscribe(subscribe: Subscribe){
            this.subscribe = subscribe
        }

        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            Log.d("HuangLJ","onCreate")
        }
        override fun onAttach(context: Context) {
            super.onAttach(context)
            attach = true
            if(request&& !checkPermission(permissions)){
                if(permissions.isNotEmpty()){
                    requestPermissions(permissions,10086)
                }
                attach = false
            }
        }
        private fun checkPermission(permissions: Array<String>): Boolean {
            val allGranted = permissions.all {
                ContextCompat.checkSelfPermission(
                    context!!,
                    it
                ) == PERMISSION_GRANTED
            }
            if (allGranted) return true
            return false
        }

        override fun onAttachFragment(childFragment: Fragment) {
            super.onAttachFragment(childFragment)
            attach = true
            if(request && permissions.isNotEmpty()&&!checkPermission(permissions)){
                requestPermissions(permissions,10086)
                attach = false
            }
        }

        override fun onDetach() {
            super.onDetach()
            subscribe = null
        }

        override fun onDestroy() {
            super.onDestroy()
            subscribe = null
        }
    }
    interface Subscribe{
        fun onResult(allGranted:Boolean)
    }
}